package com.zxh.blog.shiro;

import com.zxh.blog.domain.Permission;
import com.zxh.blog.domain.Role;
import com.zxh.blog.domain.User;
import com.zxh.blog.service.PermissionService;
import com.zxh.blog.service.RoleService;
import com.zxh.blog.service.UserService;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {

	@Autowired
	UserService userService;

	@Autowired
	RoleService roleService;

	@Autowired
	PermissionService permissionService;

	/**
	 * 授权
	 * @param principal
	 * @return
	 */
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		String userName = (String) principal.getPrimaryPrincipal();
		SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
		User user = userService.findUserByUserName(userName);
		Role role = roleService.findRoleByUser(user);
		List<Permission> adminPermissions = permissionService.findPermissionsByRoleId(role);
		Set<String> permissions = new HashSet();

		for(Permission permission:adminPermissions){
			if(StringUtils.isNotBlank(permission.getPermission())){
				permissions.add(permission.getPermission());
			}
		}
		HashSet<String> roleSet = new HashSet<String>();
		roleSet.add(role.getDescription());
		authorizationInfo.setRoles(roleSet);
		authorizationInfo.setStringPermissions(permissions);
		return authorizationInfo;
	}

	/**
	 * 认证
	 * @param token
	 * @return
	 * @throws AuthenticationException
	 */
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)  {
		String userName = (String)token.getPrincipal();
		User user = userService.findUserByUserName(userName);
		if(user == null) {
			throw new UnknownAccountException();//没找到帐号
		}
		//交给AuthenticatingRealm使用CredentialsMatcher进行密码匹配，如果觉得人家的不好可以自定义实现
		SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
				user.getUsername(),
				user.getPassword(),
				getName()  //realm name
		);
		return authenticationInfo;
	}
}
